<!--
	作者：offline
	时间：2018-11-28
	描述：采购订单详情
-->
<template>
  <div class="m-view-unPublishedPurOrderComponents m-window">
    <div class="m-condition">
      <el-row :gutter="5" class="m-floatright">
        <el-col :span="24">
          <el-row :gutter="10">
            <el-col :span="2" v-if="showRecordBtn">
              <el-button type="primary" @click="viewChange" :disabled="btnDis" class="m-minBtn">变更记录</el-button>
            </el-col>
            <el-col :span="2" v-if="ordStatus==3||ordStatus==4">
              <el-button type="primary" @click="back2" :disabled="btnDis" class="m-minBtn">退回</el-button>
            </el-col>
            <el-col :span="2" v-if="conBtnShow">
              <el-button type="primary" @click="confirm" :disabled="btnDis" class="m-minBtn">确认</el-button>
            </el-col>
            <el-col :span="2" v-if="btnShow">
              <el-button type="primary" @click="published" :disabled="btnDis" class="m-minBtn">发布</el-button>
            </el-col>
            <el-col :span="2">
              <el-button @click="printOrderDetail" :disabled="btnDis" type="primary">订单打印</el-button>
            </el-col>
            <el-col :span="2" class="m-minBtn">
              <el-button @click="cancel" :disabled="btnDis">返回</el-button>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-form
          :model="ruleForm"
          ref="ruleForm"
          label-width="70px"
          :inline-message="true"
          label-position="left"
        >
          <el-col :span="7">
            <el-form-item label="采购单号">
              <el-input v-model="ruleForm.purOrdNo" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="供应商">
              <el-input v-model="ruleForm.supplierName" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="订单日期">
              <el-date-picker
                v-model="ruleForm.purOrdDate"
                type="date"
                placeholder="订单日期"
                value-format="yyyy-MM-dd"
                disabled
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="6">
            <el-form-item label="订单类型">
              <el-input v-model="ruleForm.purOrdType" placeholder="订单类型" disabled v-if="false"></el-input>
              <el-input v-model="ruleForm.purOrdTypeName" disabled v-if="true"></el-input>
            </el-form-item>
          </el-col>-->
          <!-- <el-col :span="6">
          <el-form-item label="采购组织">-->
          <!-- <el-input v-model="ruleForm.purOrgCode" placeholder="采购组织"  disabled></el-input> -->
          <!-- <el-select v-model="ruleForm.purOrgCode" clearable disabled>
                <el-option
                  v-for="item in purOrgOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>-->

          <el-col :span="7">
            <el-form-item label="公司">
              <el-input v-model="ruleForm.companyName" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="付款条件">
              <el-input v-model="ruleForm.payment" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="采购组">
              <el-input v-model="ruleForm.purGroupName" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="税率">
              <el-input
                v-model="ruleForm.rate"
                disabled
                :class="{'isChange':rateChanged&&ordStatus!=3}"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="ruleForm.remark" placeholder="(100字)" maxlength="100" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
    </div>
    <div class="m-flowInfo">
      <ag-grid-vue
        class="m-agTableContent ag-theme-balham"
        :gridOptions="gridOptions"
        :columnDefs="columnDefs"
        rowSelection="single"
        v-loading="loading"
        ref="orderGird"
      ></ag-grid-vue>
    </div>
    <!-- <div class="m-mainContent m-top3" v-if="this.getClickValue.flagUI != 'flowInfo'">
      <ag-grid-vue
        class="m-agTableContent ag-theme-balham"
        :gridOptions="gridOptions"
        :columnDefs="columnDefs"
        rowSelection="single"
        v-loading="loading"
        ref="orderGird"
      ></ag-grid-vue>
    </div>
    <div class="m-flowInfo m-top3" v-if="this.getClickValue.flagUI == 'flowInfo'">
      <ag-grid-vue
        class="m-agTableContent ag-theme-balham"
        :gridOptions="gridOptions"
        :columnDefs="columnDefs"
        rowSelection="single"
        v-loading="loading"
        ref="orderGird"
      ></ag-grid-vue>
    </div>-->
    <!-- 查看委外订单组件信息 -->
    <el-dialog
      title="组件信息"
      v-if="dialogVisible"
      :visible.sync="dialogVisible"
      width="70%"
      :before-close="handleClose"
      v-dialogDrag
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-row :gutter="10">
        <el-form
          :model="dialogForm"
          ref="dialogForm"
          label-width="70px"
          :inline-message="true"
          label-position="left"
        >
          <el-col :span="8">
            <el-form-item label="物料描述" class="rightItem">
              <el-input v-model="dialogForm.matName" placeholder="物料描述" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="源物料编码" class="rightItem" label-width="90px">
              <el-input v-model="dialogForm.matCode" placeholder="物料编码" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="交货日期" class="rightItem">
              <el-date-picker
                disabled
                v-model="dialogForm.deliveryDate"
                type="date"
                placeholder="交货日期"
                value-format="yyyy-MM-dd"
                :editable="false"
                :clearable="false"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="工厂" class="rightItem">
              <el-input v-model="dialogForm.plantName" placeholder="工厂名称" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="数量" class="rightItem">
              <el-input v-model="dialogForm.orderAmount" placeholder="数量" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div class="dialogBody">
        <agGridComponents
          ref="dialogAgGrid"
          :getColumnDefs="dialogColumnDefs"
          :getGridOptions="dialogOptions"
        ></agGridComponents>
      </div>
      <!-- <div slot="footer" class="dialog-footer">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          @prev-click="handlePrevClick"
          @next-click="handleNextClick"
          :current-page="currentPage"
          :page-sizes="[30,50,100,150,200]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </div>-->
    </el-dialog>
    <!-- 变更记录弹窗 -->
    <recordDialog
      v-if="recordVisible"
      :dialogVisible="recordVisible"
      @closeDialog="recordVisible=false"
      :purOrdNo="ruleForm.purOrdNo"
    ></recordDialog>
  </div>
</template>

<script>
import localeText from "@/i18n/agGridText";
// import authInfo from "@/public/authInfo.js";
import _Api from "@/api";
import supplierInfo from "@/public/supplierInfo.js";
import { orderType, purOrgCode } from "@/public/enum.js";
import addOperation from "@/public/addOperation.js";
import buttonLink from "@/components/buttonLink.js";
import constant from "@/public/constant";
import utils from "@/public/utils";
import fileStream from "@/public/fileStream.js";
import agGridComponents from "@/components/agGridComponents.js";
import recordDialog from "./changeRecordDialog";
import { startPrint } from 'lesso-common/webprint'
import apienv from '@/api/env';


const ENV = apienv[constant.appenv]


export default {
  data () {
    return {
      btnDis: false,
      purOrd: "",
      supplierName: "",
      orderDate: "",
      companyName: "",
      purOrg: "",
      purGroup: "",
      paymentCondition: "",
      remark: "",
      normalSize: false,
      loading: false,
      dialogSize: document.body.clientWidth,
      btnShow: true,
      conBtnShow: true,
      totalMoney: 0,
      ruleForm: {},
      rowData: [],
      supplierInfo: [],
      headerInfo: "",
      purOrgOptions: [],
      // 组件信息弹窗表单  
      dialogForm: {},
      // 委外物料详细数据
      outSourceData: [],
      // 组件信息弹窗是否显示   
      dialogVisible: false,
      // 变更记录弹窗显示
      recordVisible: false,
      // 变更记录按钮显示
      showRecordBtn: false,
      rateChanged: false
    }
  },
  watch: {
    // dialogSize (val) {
    //   var that = this;
    //   this.dialogSize = val;
    //   this.$nextTick(_ => {
    //     that.gridOptions.api.sizeColumnsToFit();
    //   })
    // }
  },
  components: {
    agGridComponents,
    recordDialog
  },
  methods: {
    //  弹窗关闭回调
    handleClose () {
      this.dialogVisible = false
    },
    // 查看变更记录
    viewChange () {
      this.recordVisible = true
    },
    // 点击查看打开组件信息弹窗
    setClickValue (params) {
      console.log('组件信息', params.data)
      const { purchaseorderunits, matName, matCode, deliveryDate, orderAmount, itemType } = params.data
      let totalAmount = ''
      if (itemType == 3) {
        if (purchaseorderunits.length > 0) {
          const { plantName } = purchaseorderunits[0]
          this.dialogForm = {
            matName,
            matCode,
            deliveryDate,
            orderAmount,
            plantName
          }
          purchaseorderunits.forEach(unit => {
            totalAmount = addOperation.accAdd(
              unit.amount,
              totalAmount
            )
          })
          this.dialogVisible = true
          this.$nextTick(_ => {
            this.$refs.dialogAgGrid.gridOptions.api.setRowData(purchaseorderunits)
            this.$refs.dialogAgGrid.gridOptions.api.setPinnedBottomRowData([{
              matName: "合计",
              amount: totalAmount
            }])
          })
        } else {
          this.$alert("组件信息为空！", {
            showClose: false,
            confirmButton: "确定",
            customClass: "alertFailure"
          })
        }
      } else {
        this.$alert("非委外订单组件信息为空！", {
          showClose: false,
          confirmButton: "确定",
          customClass: "alertFailure"
        })
      }
    },
    confirm () {
      var that = this;
      // this.$confirm("是否确认该数据？","消息提示",{
      // 	confirmButtonText:"确定",
      // 	cancelButtonText:"取消",
      // 	distinguishCancelAndClose:true,
      // 	showInput:true,
      // 	inputValue:'确认',
      // 	center:true
      // }).then(()=>{
      // 	var obj = {
      // 		purOrdNo : this.getClickValue.purOrdNo,
      // 		id : this.getClickValue.id,
      // 		confirmerId:this.$global.user.id,
      // 		confirmer:this.$global.user.employeeName
      // 	};
      // 	_Api.confirmPurOrder(obj).then(function(response){
      // 		var data = response.data;
      // 		if(data.code == "1")
      // 		{
      // 			that.$message({
      // 				message: "操作成功",
      // 				type: "success"
      // 			});
      // 			that.cancel();
      // 		}else{
      // 			that.$alert(data.info, {
      // 				showClose: false,
      // 				confirmButton: "确定",
      // 				customClass: "alertFailure"
      // 			});
      // 		}
      // 	}).catch(()=>{
      // 		that.$alert(err.data.message, {
      // 			showClose: false,
      // 			confirmButton: "确定",
      // 			customClass: "alertFailure"
      // 		});
      // 	})
      // }).catch(()=>{})
      this.$confirm('是否确认该数据？', '提示', {
        confirmButtonText: "确定",
        cancelButtonText: "取消"
      }).then(({ value }) => {
        var tblPurchaseordermxs = []
        this.rowData.forEach(row => {
          tblPurchaseordermxs.push(
            {
              purOrdNo: row.purOrdNo,//订单编号
              purOrdMxNo: row.purOrdMxNo,//订单行号
              id: row.id, //明细Id
              matCode: row.matCode, //物料编码
              changeField: row.changeField
            }
          )
        })
        var obj = {
          purOrdNo: that.getClickValue.purOrdNo,
          id: that.getClickValue.id,
          confirmerId: this.$global.user.id,
          confirmer: this.$global.user.employeeName,
          tblPurchaseordermxs: tblPurchaseordermxs
        }
        _Api.confirmPurOrder(obj).then(function (response) {
          var data = response.data;
          if (data.code == "1") {
            that.$message({
              message: "操作成功",
              type: "success"
            });
            that.cancel();
          } else {
            that.$alert("操作失败！：" + data.info, {
              showClose: false,
              confirmButton: "确定",
              customClass: "alertFailure"
            });
          }
        }).catch((err) => {
          that.$alert(err.data.message, {
            showClose: false,
            confirmButton: "确定",
            customClass: "alertFailure"
          });
        })
      }).catch(() => { })
    },
    // 退回
    back2 () {
      this.btnDis = true
      var idArr = [] //明细主键id集合
      this.rowData.forEach(row => {
        idArr.push({
          id: row.id
        })
      })
      var pramas = {
        tblPurchaseorderbill: {
          purOrdNo: this.getClickValue.purOrdNo,//采购订单号
          id: this.getClickValue.id //主表主键
        },
        tblPurchaseordermxs: idArr
      }
      if (this.ordStatus == 4) {
        this.$confirm('是否退回该订单？', '提示', {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: 'warning'
        }).then(({ value }) => {
          this.backOrder(pramas)
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消退回'
          });
          this.btnDis = false
        })
      } else if (this.ordStatus === 3) {
        var obj = {}
        obj.eqParams = {
          purOrdNo: this.getClickValue.purOrdNo,
          supplierCode: this.getClickValue.supplierCode
        };
        // 查询该订单是否已创建送货单
        _Api.getDeliveryList(obj).then(res => {
          let data = res.data
          if (data.code == "1") {
            if (data.total == 0) {
              this.$confirm('退回将冻结该订单的所有后续操作，是否确认？', '提示', {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: 'warning'
              }).then(() => {
                this.backOrder(pramas)
              }).catch(() => {
                this.$message({
                  type: 'info',
                  message: '已取消退回'
                });
                this.btnDis = false
              })
            } else if (data.total > 0) {
              this.$confirm('该订单已创建送货单，退回将冻结该订单的所有后续操作，是否确认？', '提示', {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: 'warning'
              }).then(() => {
                this.backOrder(pramas)
              }).catch(() => {
                this.$message({
                  type: 'info',
                  message: '已取消退回'
                });
                this.btnDis = false
              })
            }
          }
        })
      }
    },
    // 调用订单退回接口
    backOrder (obj) {
      var that = this
      _Api.returnPurOder(obj).then(function (response) {
        var data = response.data;
        if (data.code == "1") {
          that.$message({
            message: "操作成功,订单已退回",
            type: "success"
          });
          that.cancel();
          that.btnDis = false
        } else {
          that.btnDis = false
          that.$alert(data.info, {
            showClose: false,
            confirmButton: "确定",
            customClass: "alertFailure"
          });
        }
      }).catch((err) => {
        that.$alert(err.data.message, {
          showClose: false,
          confirmButton: "确定",
          customClass: "alertFailure"
        });
        that.btnDis = false
      })
    },
    back () {
      var that = this;
      // this.$confirm("是否确认该数据？","消息提示",{
      // 	confirmButtonText:"确定",
      // 	cancelButtonText:"取消",
      // 	distinguishCancelAndClose:true,
      // 	showInput:true,
      // 	inputValue:'确认',
      // 	center:true
      // }).then(()=>{
      // 	var obj = {
      // 		purOrdNo : this.getClickValue.purOrdNo,
      // 		id : this.getClickValue.id,
      // 		confirmerId:this.$global.user.id,
      // 		confirmer:this.$global.user.employeeName
      // 	};
      // 	_Api.confirmPurOrder(obj).then(function(response){
      // 		var data = response.data;
      // 		if(data.code == "1")
      // 		{
      // 			that.$message({
      // 				message: "操作成功",
      // 				type: "success"
      // 			});
      // 			that.cancel();
      // 		}else{
      // 			that.$alert("操作失败！：" + data.info, {
      // 				showClose: false,
      // 				confirmButton: "确定",
      // 				customClass: "alertFailure"
      // 			});
      // 		}
      // 	}).catch(()=>{
      // 		that.$alert("操作失败！", {
      // 			showClose: false,
      // 			confirmButton: "确定",
      // 			customClass: "alertFailure"
      // 		});
      // 	})
      // }).catch(()=>{})
      this.$prompt('是否退回该数据？', '提示', {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputValue: "退回",
        inputValidator: function (value) {
          if (value.length > 10)
            return false;
        },
        inputErrorMessage: '退回信息请控制在10位字符以内！'
      }).then(({ value }) => {
        var obj = {
          purOrdNo: that.getClickValue.purOrdNo,
          id: that.getClickValue.id,
          confirmerId: this.$global.user.id,
          confirmer: this.$global.user.employeeName
        }
        _Api.confirmPurOrder(obj).then(function (response) {
          var data = response.data;
          if (data.code == "1") {
            that.$message({
              message: "操作成功",
              type: "success"
            });
            that.cancel();
          } else {
            that.$alert(data.info, {
              showClose: false,
              confirmButton: "确定",
              customClass: "alertFailure"
            });
          }
        }).catch((err) => {
          that.$alert(err.data.message, {
            showClose: false,
            confirmButton: "确定",
            customClass: "alertFailure"
          });
        })
      }).catch(() => { })
    },
    cancel: function () {
      //返回
      this.$emit("cancelComponents", true);
    },
    published () {
      //发布
      if (this.ordStatus === 1) {
        //未发布采购订单执行发布操作
        var that = this;
        this.$confirm("是否发布该数据？", "消息提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          distinguishCancelAndClose: true
        }).then(() => {
          var obj = {};
          obj.purOrdNo = that.ruleForm.purOrdNo;
          obj.purOrdType = that.ruleForm.purOrdType;
          obj.supplierCode = that.ruleForm.supplierCode;
          obj.supplierName = that.ruleForm.supplierName;
          obj.supplierId = that.ruleForm.supplierId;
          obj.purOrdDate = that.ruleForm.purOrdDate;
          obj.companyCode = that.ruleForm.companyCode;
          obj.companyName = that.ruleForm.companyName;
          obj.companyId = that.ruleForm.companyId;
          obj.purGroup = that.ruleForm.purGroup;
          obj.purOrgCode = that.ruleForm.purOrgCode;
          obj.purGroupName = that.ruleForm.purGroupName;
          obj.payment = that.ruleForm.payment;
          obj.remark = that.ruleForm.remark;
          obj.paymentCode = that.ruleForm.paymentCode;
          obj.releaserId = this.$global.user.id;
          obj.releaser = this.$global.user.employeeName;
          obj.creatorId = that.headerInfo.creatorId;
          obj.creator = that.headerInfo.creator
          obj.createDate = that.headerInfo.createDate;
          obj.purDetail = that.rowData;
          that.btnDis = true;
          _Api.publishPurOrder(obj).then(function (response) {
            var data = response.data;
            that.btnDis = false;
            if (data.code == "1") {
              that.$message({
                message: "操作成功",
                type: "success"
              });
              that.cancel();
            } else {
              that.$alert(data.info, {
                showClose: false,
                confirmButton: "确定",
                customClass: "alertFailure"
              });
            }
          }).catch((err) => {
            that.$alert(err.data.message, {
              showClose: false,
              confirmButton: "确定",
              customClass: "alertFailure"
            });
          })
        }).catch(() => { })
      }
    },
    getContextMenuItems () {
      return [];
    },
    // 设置底部合计栏数据
    createBottomRow (count, prefix) {
      var result = [{
        matName: "合计",
        unitMoney: this.totalMoney,
        subassembly: ''
      }];
      return result;
    },
    // 获取未发布订单详情sap
    getPurDetailsOfSap (params) {
      if (params) {

        var that = this;
        var obj = {
          purOrdNo: params
        };
        that.loading = true
        _Api.getPurDetailsOfSap(obj).then(function (response) {
          var data = response.data;
          that.loading = false
          if (data.code == "1") {
            if (data.total > 0) {
              that.headerInfo = data.rows.tblPurchaseorderbill;
              that.showRecordBtn = that.headerInfo.isChange == 1 ? true : false
              const { rate } = that.headerInfo
              that.ruleForm = {
                ...that.headerInfo,
                rate: `${rate * 100}%`
              };
              orderType.forEach(item => {
                if (item.value == that.headerInfo.purOrdType) {
                  that.$set(that.ruleForm, 'purOrdType', item.value);
                  that.$set(that.ruleForm, 'purOrdTypeName', item.label);
                }
              })
              that.rowData = data.rows.tblPurchaseordermx.splice(0);
              // 合并订单明细中组件数组   
              that.rowData.forEach(row => {
                row.subassembly = row.itemType == 3 ? "查看" : ''
                that.outSourceData = [...row.purchaseorderunits, ...that.outSourceData]
                if (Array.isArray(row.changeField) && row.changeField.length > 0) {
                  if (row.changeField.indexOf('rate') > -1) {
                    that.rateChanged = true
                  }
                }
              })
              // 判断明细中单位与价格单位是否一致
              let equal = that.rowData.every(item => {
                return item.priceUnit == item.unitCode
              })
              if (equal) {
                // 隐藏价格数量和价格单位
                that.$refs.orderGird.gridOptions.columnApi.setColumnVisible('priceAmount', false);
                that.$refs.orderGird.gridOptions.columnApi.setColumnVisible('priceUnit', false);
              }
              that.gridOptions.api.setRowData(that.rowData);
              let allColumnIds = [];
              that.gridOptions.columnApi.getAllColumns().forEach(function (column) {
                allColumnIds.push(column.colId);
              });
              that.$refs.orderGird.gridOptions.api.forEachNode(function (node) {
                that.totalMoney = addOperation.accAdd(
                  node.data.unitMoney,
                  that.totalMoney
                )
                that.$refs.orderGird.gridOptions.api.setPinnedBottomRowData(
                  that.createBottomRow(1, "Bottom")
                );
              });
              that.gridOptions.columnApi.autoSizeColumns(allColumnIds);
              //that.gridOptions.api.setRowData(data.rows.splice(0));
            }
            else
              that.gridOptions.api.setRowData([]);
          } else {
            that.$alert(data.info, {
              showClose: false,
              confirmButton: "确定",
              customClass: "alertFailure"
            });
          }
        }).catch((err) => {
          that.loading = false
          that.$alert(err.data.message, {
            showClose: false,
            confirmButton: "确定",
            customClass: "alertFailure"
          });
        })
      }
    },
    // 获取已发布订单详情srm
    getPurDetailsOfSrm (params) {
      if (params) {
        var that = this;
        var obj = {
          id: params
        };
        that.loading = true
        _Api.getPurDetailOfSrm(obj).then(function (response) {
          var data = response.data;
          that.loading = false
          if (data.code == "1") {
            if (data.total > 0) {
              that.headerInfo = data.rows.tblPurchaseorderbill;
              that.showRecordBtn = that.headerInfo.isChange == 1 ? true : false
              const { rate } = that.headerInfo
              that.ruleForm = {
                ...that.headerInfo,
                rate: `${rate * 100}%`
              };
              for (let a in orderType) {
                if (orderType[a].value == that.headerInfo.purOrdType) {
                  that.$set(that.ruleForm, 'purOrdType', orderType[a].value);
                  that.$set(that.ruleForm, 'purOrdTypeName', orderType[a].label);
                }
              }
              that.rowData = data.rows.tblPurchaseordermx.splice(0);
              that.rowData.forEach((row, index) => {
                row.subassembly = row.itemType == 3 ? "查看" : ''
                that.outSourceData = [...that.outSourceData, ...row.purchaseorderunits]
                if (Array.isArray(row.changeField) && row.changeField.length > 0) {
                  if (row.changeField.indexOf('rate') > -1) {
                    that.rateChanged = true
                  }
                }
              })
              // 判断明细中单位与价格单位是否一致
              let equal = that.rowData.every(item => {
                return item.priceUnit == item.unitCode
              })
              if (equal) {
                // 隐藏价格数量和价格单位
                that.$refs.orderGird.gridOptions.columnApi.setColumnVisible('priceAmount', false);
                that.$refs.orderGird.gridOptions.columnApi.setColumnVisible('priceUnit', false);
              }
              that.gridOptions.api.setRowData(that.rowData);
              let allColumnIds = [];
              that.gridOptions.columnApi.getAllColumns().forEach(function (column) {
                allColumnIds.push(column.colId);
              });
              that.$refs.orderGird.gridOptions.api.forEachNode(function (node) {
                that.totalMoney = addOperation.accAdd(
                  node.data.unitMoney,
                  that.totalMoney
                );
                that.$refs.orderGird.gridOptions.api.setPinnedBottomRowData(
                  that.createBottomRow(1, "Bottom")
                );
              });
              that.gridOptions.columnApi.autoSizeColumns(allColumnIds);
              //that.gridOptions.api.setRowData(data.rows.splice(0));
            }
            else
              that.gridOptions.api.setRowData([]);
          } else {
            that.$alert(data.info, {
              showClose: false,
              confirmButton: "确定",
              customClass: "alertFailure"
            });
          }
        }).catch((err) => {
          that.loading = false
          that.$alert(err.data.message, {
            showClose: false,
            confirmButton: "确定",
            customClass: "alertFailure"
          });
        })
      }
    },
    // 打印采购订单详情
    printOrder () {
      const { companyName, payment, purOrdNo, supplierName, purOrdDate, rate, linkMan, phone, fax } = this.headerInfo
      let totalMoney = utils.convertCurrency(this.totalMoney)
      let tempArr = []
      let outArr = []
      let detailRows = this.rowData
      let len = this.outSourceData.length
      let type = ''
      //  判断价格单位是否与单位相等  
      let isEqual = detailRows.every(item => {
        return item.unitCode == item.priceUnit
      })
      // 根据条件选择相应的打印模板   
      if (isEqual) {
        if (len > 0) {
          type = "outsourceOrderB_pc"
        } else {
          type = "printOrderB_pc"
        }
      } else {
        if (len > 0) {
          type = "outsourceOrder_pc"
        } else {
          type = "printOrder_pc"
        }
      }
      // 格式化含税单价
      function formatPrice (value) {
        if (value) {
          let strNum = value.toString().split('.')
          if (strNum.length == 2 && strNum[1].length == 4) {
            if (strNum[1].charAt(2) == '0' && strNum[1].charAt(3) == '0') {
              return Number(value).toFixed(2);
            } else if (strNum[1].charAt(2) != '0' && strNum[1].charAt(3) == '0') {
              return Number(value).toFixed(3)
            } else {
              return value
            }
          }
        }
      }

      for (let i in detailRows) {
        const {
          matCode,
          matName,
          orderAmount,
          priceAmount,
          priceUnit,
          purOrdMxNo,
          remark,
          unitMoney,
          unitPrice,
          unitCode,
          deliveryDate
        } = detailRows[i]
        // obj订单订单模板主表内容
        let obj = {
          matCode, //物料编码
          matName, //产品名称
          orderAmount,//订单数量 
          priceAmount, //价格数量
          priceUnit, //价格单位
          purOrdMxNo, //行号
          remark: this.headerInfo.remark,
          tblRemark: this.headerInfo.remark,//订单备注
          mxremark: remark, //物料备注
          unitMoney, //含税金额
          totalMoney: totalMoney,//合计金额大写
          unitPrice: formatPrice(unitPrice), //含税单价
          unitCode, //单位
          rate, //税率
          linkMan,//供应商联系人
          phone, //供应商联系电话
          fax,//供应商传真号码
          deliveryDate,//交货日期
          companyName, //公司名称
          payment, //付款条件
          supplierName,// 供应商名称
          confirmDate: purOrdDate, //订单签订日期
          purOrdNo, //订单编号
          address: detailRows[0].address //交货地址
        };
        tempArr.push(obj)
      }
      // 设置委外明细打印模板数据
      this.outSourceData.forEach((item, index) => {
        const { matCode, matName, amount, remark, unitCode, purOrdNo } = item
        outArr.push({
          matCode,
          matName,
          amount,
          remark,
          unitCode,
          purOrdNo,
          supplierName,
          num: index + 1
        })
      })
      if (constant.printType == 'local') {
        ipcRenderer.send("IPCR_M_PRINTLOCAL", {
          type: type,
          rows: tempArr,
          childRows: outArr,
          optype: "pr",
          isdefaultp: 1//控制是否直接打印,0为选择打印、1为直接打印
        })
      } else {
        fileStream.getFileInfo(type).then((data) => {
          ipcRenderer.send("IPCR_M_PRINT", {
            type: type,
            rows: tempArr,
            childRows: outArr,
            optype: "pr",
            groupName: data.groupName,
            url: data.url,
            isdefaultp: 1//控制是否直接打印,0为选择打印、1为直接打印
          });
        }).catch((err) => {
          this.$alert(err, {
            showClose: false,
            confirmButton: "确定",
            customClass: "alertFailure"
          });
        })
      }
    },
    // web版打印訂單詳情
    printOrderTemp () {
      const { supplierCode, id, purOrdNo } = this.headerInfo
      let detailRows = this.rowData
      let len = this.outSourceData.length
      let type = ''
      let itemType = ''
      let params = {}
      let dataUrl = ''
      //  判断价格单位是否与单位相等  
      let isEqual = detailRows.every(item => {
        return item.unitCode == item.priceUnit
      })
      // 根据条件选择相应的打印模板   
      if (isEqual) {
        if (len > 0) {
          type = "outsourceOrderB"
          itemType = 3
        } else {
          type = "printOrderB"
          itemType = 1
        }
      } else {
        if (len > 0) {
          type = "outsourceOrder"
          itemType = 3
        } else {
          type = "printOrder"
          itemType = 1
        }
      }
      if (this.ordStatus == 1) {
        params = {
          'token': '',
          'purOrdNo': purOrdNo
        }
        dataUrl = 'tblPurchaseorderbill/purchasebillSapInfo'
      } else {
        params = {
          'token': '',
          'id': id,
          'supplierCode': supplierCode,
          'itemType': itemType
        }
        dataUrl = 'tblPurchaseorderbill/purchasebillInfo'
      }
      fileStream.getFileInfo(type).then((data) => {
        startPrint({
          basicUrl: ENV['srm'], //权限接口地址
          reportUrl: `${ENV['srm']}download2?viewPath=${data.url}&groupName=${data.groupName}`, //打印模板地址
          dataUrl: dataUrl, //数据接口地址
          params: params, //参数对象
          printType: 'preview'     // 打印方式print直接打印，preview先预览
        })
      }).catch((err) => {
        that.$alert(err, {
          showClose: false,
          confirmButton: "确定",
          customClass: "alertFailure"
        });
      })
    },
    // 打印订单详情
    printOrderDetail () {
      if (constant.userAgent == 'web') {
        this.printOrderTemp()
      } else {
        this.printOrder()
      }
    }
  },
  beforeMount () {
    let that = this
    this.gridOptions = {
      context: {
        componentParent: this
      },
      enableColResize: true,
      localeText: localeText,
      //   getContextMenuItems: this.getContextMenuItems,
      pinnedBottomRowData: this.createBottomRow(1, "Bottom"),
      getRowStyle: function (params) {
        if (params.node.rowPinned) {
          return { 'color': 'red', 'font-weight': "bold" }
        }
      }
    };
    this.columnDefs = [
      { headerName: "行号", field: "purOrdMxNo", width: 70 },
      { headerName: "物料号", field: "matCode", width: 120 },
      { headerName: "物料描述", field: "matName", width: 160, tooltipField: 'matName' },
      {
        headerName: "数量",
        field: "orderAmount",
        width: 70,
        cellStyle: function (params) {
          const { data: { changeField } } = params
          if (Array.isArray(changeField) && changeField.length > 0 && that.ordStatus != 3) {
            if (changeField.indexOf('orderAmount') > -1) {
              return {
                'color': 'red',
              }
            }
          }
        }
      },
      { headerName: "单位", field: "unitCode", width: 70 },
      {
        headerName: "价格数量",
        field: "priceAmount",
        width: 90,
        cellStyle: function (params) {
          const { data: { changeField } } = params
          if (Array.isArray(changeField) && changeField.length > 0 && that.ordStatus != 3) {
            if (changeField.indexOf('priceAmount') > -1) {
              return {
                'color': 'red',
              }
            }
          }
        }
      },
      { headerName: "价格单位", field: "priceUnit", width: 90 },
      {
        headerName: "含税单价",
        field: "unitPrice",
        width: 100,
        cellRenderer: function (params) {
          if (params.value) {
            let strNum = params.value.toString().split('.')
            if (strNum.length == 2 && strNum[1].length == 4) {
              if (strNum[1].charAt(2) == '0' && strNum[1].charAt(3) == '0') {
                return Number(params.value).toFixed(2);
              } else if (strNum[1].charAt(2) != '0' && strNum[1].charAt(3) == '0') {
                return Number(params.value).toFixed(3)
              } else {
                return params.value
              }
            }
          }
        },
        cellStyle: function (params) {
          const { data: { changeField } } = params
          if (Array.isArray(changeField) && changeField.length > 0 && that.ordStatus != 3) {
            if (changeField.indexOf('unitPrice') > -1) {
              return {
                'color': 'red',
                "text-align": "right"
              }
            } else {
              return {
                "text-align": "right"
              }
            }
          } else {
            return {
              "text-align": "right"
            }
          }
        }
      },
      {
        headerName: "含税金额",
        field: "unitMoney",
        width: 100,
        cellRenderer: function (params) {
          if (params.value) {
            // 含税金额转换为千分位格式 且保留两位小数
            params.value = String(params.value.toFixed(2));
            let re = /(-?\d+)(\d{3})/;
            while (re.test(params.value)) {
              params.value = params.value.replace(re, "$1,$2");
            }
            return params.value;
          }
        },
        cellStyle: {
          "text-align": "right"
        }
      },
      {
        headerName: "备注",
        field: "remark",
        width: 100,
        tooltipField: 'remark',
        cellStyle: function (params) {
          const { data: { changeField } } = params
          if (Array.isArray(changeField) && changeField.length > 0 && that.ordStatus != 3) {
            if (changeField.indexOf('remark') > -1) {
              return {
                'color': 'red',
              }
            }
          }
        }
      },
      // { headerName: "税率", field: "rate" },
      {
        headerName: "批次",
        field: "batch",
        width: 90,
        cellStyle: function (params) {
          const { data: { changeField } } = params
          if (Array.isArray(changeField) && changeField.length > 0 && that.ordStatus != 3) {
            if (changeField.indexOf('batch') > -1) {
              return {
                'color': 'red',
              }
            }
          }
        }
      },
      {
        headerName: "计划交货日期",
        field: "deliveryDate",
        width: 130,
        cellRenderer: function (params) {
          if (params.value)
            return new Date(Date.parse(params.value.replace(/-/g, "/"))).Format("yyyy-MM-dd");
        }
      },
      {
        headerName: "防伪标识",
        field: "isBarCode",
        width: 70,
        // cellEditor: SetCheckBoxEditor,
        cellRenderer: function (params) {
          if (params.value === 1)
            return '<span class="ag-icon ag-icon-checkbox-checked"></span>'
          else
            return '<span class="ag-icon ag-icon-checkbox-unchecked"></span>'
        }
      },
      ,
      {
        headerName: "关闭标识",
        field: "comFlag",
        width: 70,
        // cellEditor: SetCheckBoxEditor,
        cellRenderer: function (params) {
          if (params.value === 'X')
            return '<span class="ag-icon ag-icon-checkbox-checked"></span>'
          else
            return '<span class="ag-icon ag-icon-checkbox-unchecked"></span>'
        }
      },
      {
        headerName: "组件",
        field: "subassembly",
        width: 70,
        cellRenderer: buttonLink
      }
      // { headerName: "工厂", field: "plantName" }
    ]
    // 组件弹窗列表配置
    this.dialogOptions = {
      getRowStyle: function (params) {
        if (params.node.rowPinned) {
          return { 'color': 'red', 'font-weight': "bold" }
        }
      }
    }
    // 组件信息弹窗表格列配置
    this.dialogColumnDefs = [
      { headerName: "物料号", field: "matCode" },
      { headerName: "物料描述", field: "matName" },
      { headerName: "数量", field: "amount" },
      { headerName: "单位", field: "unitCode" },
      { headerName: "备注", field: "remark" },
    ]
  },
  mounted () {
    var that = this;
    // if(this.getClickValue.flagUI == 'flowInfo'){
    //   this.getClickValue.id = this.getClickValue.orderId;
    // }
    window.onresize = () => {
      return (() => {
        that.dialogSize = document.body.clientWidth;
      })();
    };
    if (this.$global.user.userTypeId == "4") {

      //				var arrayList = [];
      //				arrayList.push(this.$global.supplierData);
      this.supplierInfo.push(this.$global.supplierData);
      if (this.supplierInfo[0] == null) {
        supplierInfo.getUserInfo(this.$global.user.userName).then((supplierInfo) => {
          that.supplierInfo = supplierInfo;
        })
      }
    }
    this.purOrgOptions = purOrgCode;
    this.gridOptions.api.hideOverlay();
    if (this.ordStatus === 1) {
      //  未发布订单  
      this.btnShow = true;
      this.conBtnShow = false;
      this.getPurDetailsOfSap(this.getClickValue.purOrdNo);
    }
    else if (this.ordStatus === 2 || this.ordStatus === 3) {
      //  已发布/已确认订单 
      this.btnShow = false;
      this.conBtnShow = false;
      this.getPurDetailsOfSrm(this.getClickValue.id);
    } else if (this.ordStatus === 4) {
      //  未确认订单 
      this.btnShow = false;
      this.conBtnShow = true;
      this.getPurDetailsOfSrm(this.getClickValue.id);
    }
    // this.ruleForm = this.getClickValue;
  },
  props: ["ordStatus", "getClickValue"]
}
</script>
<style lang="less" scoped>
.m-view-unPublishedPurOrderComponents {
  .m-flowInfo {
    position: absolute;
    top: 190px;
    bottom: 5px;
    left: 0;
    right: 0;
  }
}
.isChange {
  /deep/ .el-input__inner {
    color: red !important;
  }
}
</style>